<?php
namespace App\Controllers\Message;

use App\Models\User\User;
use App\Libs\Views\Json;
use App\Libs\Base\Constant;
use App\Models\Message\Message;
use App\Models\ClassModel\ClassModel;
use App\Models\ClassModel\ClassApply;
use App\Libs\Cache\Redis;
class GetClassMessageDetail extends \App\Libs\Base\BaseAction
{
    private $prefix = 'classSuccess';

    public function execute()
    {
        $user = $this->session->user??[];
        if(empty($user)){
            return Json::view(Constant::UNLOGIN,'请登录',NULL);
        }
        if(!$this->request->hasQuery('id')){
            return Json::view(1,'缺少参数',NULL);
        }
        $msgid = $this->request->getQuery('id');
        $matchMsg = Message::findOne($msgid);
        if(empty($matchMsg)){
            return Json::view(1,'消息不存在',NULL);
        }
        if(!in_array($matchMsg->type,[2])){
            return Json::view(1,'接口调用错误',NULL);
        }
        $data = json_decode($matchMsg->data,true);
        $classid = $data['classid'];
        $classModel = ClassModel::findOne($classid);
        if(strtotime($classModel->class_stime) > time() || $classModel->class_jiesuan=='1'){
            return Json::view(1,'此次任务还没有结束，暂不能查看合格人员');
        }
        $myApply = ClassApply::findOne([
            'uid=?1 and cid=?2',
            'bind' =>[1=>$user->id,2=>$classid]
        ]);
        if(empty($myApply)){
            return Json::view(1,'您未参加此班，不能查看',NULL);
        }

        $key = $this->prefix.'-'.$classModel->class_type.'-'.$classModel->id;
        $redisResult = Redis::get($key);
        if(empty($redisResult)){
            $manager = $this->di['modelsManager']->createBuilder();
            $result =  $manager->from(array('apply'=>'App\Models\ClassModel\ClassApply'))
                ->join('App\Models\User\User','apply.uid=user.id','user')
                ->where('apply.cid=?1 and apply.is_out=1',[1=>$classid])
                ->columns(['user.username','user.avatar','user.id','apply.is_out'])
                ->getQuery()
                ->execute()->toArray();
            $num = ClassApply::count([
                'cid=?1 and is_out=1',
                'bind' => [1=>$classid]
            ]);
            $redisResult = ['userList'=>$result,'userNum'=> $num];
            Redis::setex($key, 10*24*60*60,serialize($redisResult) );
        }
        return Json::view(0,'ok',unserialize($redisResult));
    }

}
